<?php


namespace app\service;
use EasyWeChat\Factory;

class Wechat
{

    private $appid;
    private $sessionKey;

    /**
     * 构造函数
     *
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
     * @param $appid      string 小程序的appid
     */
    public function __construct($appid = '', $sessionKey = '')
    {
        $this->sessionKey = $sessionKey;
        $this->appid      = $appid;
    }


    /**
     * 检验数据的真实性，并且获取解密后的明文.
     *
     * @param $encryptedData string 加密的用户数据
     * @param $iv            string 与用户数据一同返回的初始向量
     * @param $data          string 解密后的原文
     *
     * @return bool 成功true，失败返回对应的错误码
     */
    public function decryptData($encryptedData, $iv, &$data, $wechat_info = null)
    {
        if (strlen($this->sessionKey) != 24) {
            return false;
        }
        $aesKey = base64_decode($this->sessionKey);

        if (strlen($iv) != 24) {
            return false;
        }

        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result, true);
        if ($dataObj == null) {
            if ($wechat_info) {
                $data = $wechat_info;
                return true;
            }
            return false;
        }
        if ($dataObj['watermark']['appid'] != $this->appid) {
            return false;
        }
        $data = $dataObj;
        return true;
    }

    /**
     * 订单支付完成，发送消息给店主
     * @param $address
     * @param $price
     * @param $remark
     * @param $goods_info
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function create_order_for_shop($address, $price, $remark, $goods_info)
    {

        $data = [
            'touser' => 'o-uhjw6ghsm6V5xBH4huaE0OG9As',
            'template_id' => '32yeh6nA0UbTcWd1Pmen16P9ITIFDAV6j-5mDiMggEc',
            'data' => [
                'first' => '来新订单了',
                'keyword1' => date('Y-m-d H:i:s'),
                'keyword2' => $address,
                'keyword3' => $price,
                'keyword4' => $remark,
                'remark' => '商品信息：' . $goods_info
            ],
        ];
        $this->sendTemplateMessage($data);
    }

    /**
     * 发送模板消息
     * @param $data
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function sendTemplateMessage($data) {
        trace($data);
        $app = Factory::officialAccount(config('wechat.official_account'));
        $app->template_message->send($data);
    }

}